from PySide6.QtWidgets import QDialog,QMessageBox
from sqlalchemy.orm import Session
from settings.publicvar import engine

from views.person.persontype.operationpersontype import Ui_OperationPersonType
from views.person.model.person import PersonType

class OperationPersonTypeView(QDialog,Ui_OperationPersonType):
    def __init__(self,is_state,data):
        super().__init__()
        self.setupUi(self)
        self.if_state(is_state)
        self.loadDaliogData(data)
        self.addbtn.clicked.connect(self.addFun)
        self.changebtn.clicked.connect(self.changeFun)
        self.deletebtn.clicked.connect(self.deleteFun)
        self.resetbtn.clicked.connect(self.resetFun)

    def if_state(self,is_stae):
        if is_stae=='add':
            self.changebtn.hide()
            self.deletebtn.hide()
        elif is_stae=='change':
            self.titlelable.setText('修改人员类型')
            self.addbtn.hide()
            self.deletebtn.hide()
        elif is_stae == 'delete':
            self.titlelable.setText('删除人员类型')
            self.addbtn.hide()
            self.changebtn.hide()
            self.resetbtn.hide()
        else:
            self.titlelable.setText('查看人员类型')
            self.addbtn.hide()
            self.changebtn.hide()
            self.resetbtn.hide()
            self.deletebtn.hide()

    def loadDaliogData(self,data):
        if data:
            self.idx.setText(data[0])
            self.pesontype_name.setText(data[1])
            self.mark.setText(data[2])

    def getDaliogData(self):
        idx = self.idx.text().strip()
        pesontype_name = self.pesontype_name.text().strip()
        mark =self.mark.text().strip()
        data = {'persontype':pesontype_name,'mark':mark}
        if idx:
            return (idx,data)
        else:
            return (False,data)

    def addFun(self):
        data = self.getDaliogData()
        with Session(engine) as session,session.begin():
            persontype = PersonType(**data[1])
            session.add(persontype)
            QMessageBox.information(None,'成功','你添加%s成功'%persontype.persontype)
            self.close()

    def changeFun(self):
        data = self.getDaliogData()
        with Session(engine) as session, session.begin():
            session.query(PersonType).filter(PersonType.id == data[0]).update(data[1])
            QMessageBox.information(None, '成功', '你修改%s成功' % data[1]['persontype'])
            self.close()

    def deleteFun(self):
        data = self.getDaliogData()
        with Session(engine) as session, session.begin():
            session.query(PersonType).filter(PersonType.id == data[0]).delete()
            QMessageBox.critical(None, '成功', '你删除%s成功' % data[1]['persontype'])
            self.close()

    def resetFun(self):
        self.pesontype_name.setText('')
        self.mark.setText('')
        QMessageBox.critical(None, '成功', '你重置成功')

